<template>
	<view>
		<!-- 加载 -->
		<view class="read-load" v-show="loading" :style="{'background': readTheme.background}">
			<view style="margin-bottom: 20rpx;">{{currentChapterData.title}}</view>
			<view>
				<u-loading mode="circle" style="margin-right: 10rpx;"></u-loading>加载中...
			</view>
		</view>
		<!-- 顶部标题栏 -->
		<view class="read-top" :style="{'background': readTheme.background}">
			<view v-if="iStatusBarHeight > 30" class="status-bar" :style="{ height: iStatusBarHeight + 'px','background': readTheme.background}"></view>
			<view class="top-info">
				<text class='u-line-1' style="width: 70vw;">{{chapterTitle}}</text>
				<view class="read-info" style="width: 30vw;">
					<text class="battery" :style="{'background-size': battery+'% 100%'}">{{battery}}</text>
					<text>{{currentTime}}</text>
				</view>
			</view>
		</view>
		<!-- 书籍内容 -->
		<view id="read-content" scroll-y="true" @scroll="scrollView" @click="handleToMenu" :show-scrollbar="false" style="height:100vh;">
			<view class="read-box" :style="{'background': readTheme.background,'font-size':fontSize * 2 + 'rpx','font-family':fontFamily,'padding-right':pagePadding + 'rpx','padding-left':pagePadding + 'rpx','padding-top': (iStatusBarHeight < 30 ? 0 : iStatusBarHeight) + 60 + 'px'}"
			 v-for="(item,index) in contentList" :key="index" :id="'chapter' + item.index" style="overflow: hidden;">
				<text class="read-title" :style="{'font-size':fontSize*3.2+'rpx'}">{{item.title}}</text>
				<u-parse :html="sectionDistanceFilter(item.content)" :style="{'line-height':lineDistance + 'rpx'}"></u-parse>
			</view>
		</view>

		<!-- 滚屏模式遮罩层 -->
		<view v-if="pageTurnType==1" class="scroll-wrapper" @click="handleToMenu" data-type="scroll"></view>
		<!-- 导航栏 -->
		<u-popup v-model="option" mode="top" :mask="false" z-index="1000" style="height:176rpx" :mask-custom-style="{'display':'none'}">
			<u-navbar back-text="" :title="bookName" :background="{'background': readTheme.tabBackground}" :custom-back="haneleToDetail"
			 :border-bottom="false">
				<view class="slot-wrap">
					<text @click="handleAddBookShelf">{{flag?'撤出书架':'加入书架'}}</text>
				</view>
			</u-navbar>
		</u-popup>

		<!-- 设置面板 -->
		<u-popup v-model="option" mode="bottom" :mask="false" z-index="1001" @open="optionOpen" @close="optionClose">
			<view v-show="currentPageFlag" class="slider-box" :style="{'background': readTheme.tabBackground}" @click="handleToSliderChapter">
				{{sliderChapterName}}
			</view>
			<view class="chapter-slider" :style="{'background': readTheme.tabBackground}">
				<text @click="handleToLastChapter">上一章</text>
				<view style="width:50vw;display:inline-block">
					<u-slider v-model="currentChapterIndex" height="6" @moving="currentChapterIndexChange" :active-color="readTheme.background"
					 :inactive-color="readTheme.color"></u-slider>
				</view>
				<text @click="handleToNextChapter">下一章</text>
			</view>
			<view class="read-menu">
				<u-grid :col="5" :border="false" hover-class="none">
					<u-grid-item :style="{'background': readTheme.tabBackground}" @click="handleToChapterList">
						<u-icon name="../../static/image/list.png" :size="46"></u-icon>
						<view class="grid-text">章节</view>
					</u-grid-item>
					<u-grid-item :style="{'background': readTheme.tabBackground}" @click="handleToPlay">
						<u-icon :name="playFlag?'../../static/image/pause.png':'../../static/image/play.png'" :size="46"></u-icon>
						<view class="grid-text">{{playFlag?'暂停':'播放'}}</view>
					</u-grid-item>
					<u-grid-item :style="{'background': readTheme.tabBackground}" @click="handleToBrightness">
						<u-icon name="../../static/image/screen.png" :size="46"></u-icon>
						<view class="grid-text">亮度</view>
					</u-grid-item>
					<u-grid-item :style="{'background': readTheme.tabBackground}" @click="handleToChangeTheme">
						<u-icon :name="'../../static/image/'+readTheme.icon+'.png'" :size="46"></u-icon>
						<view class="grid-text">{{readTheme.item}}</view>
					</u-grid-item>
					<u-grid-item :style="{'background': readTheme.tabBackground}" @click="handleToSetting">
						<u-icon name="../../static/image/setting.png" :size="46"></u-icon>
						<view class="grid-text">设置</view>
					</u-grid-item>
				</u-grid>
			</view>
		</u-popup>

		<!-- 亮度设置 -->
		<u-popup v-model="brightness" mode="bottom" :mask="false">
			<view class="screen-box" :style="{'background': readTheme.tabBackground}">
				<u-icon name="minus-circle" size="40"></u-icon>
				<view style="width:50vw;display:inline-block;padding: 0 8rpx;">
					<u-slider v-model="brightnessValue" height="10" block-width="60"></u-slider>
				</view>
				<u-icon name="plus-circle" size="40"></u-icon>
				<view style="display: flex;align-items: center;">
					<text style="margin-right: 10rpx;">随系统</text>
					<u-switch v-model="defaultBrightnessChecked" size="36"></u-switch>
				</view>
			</view>
		</u-popup>

		<!-- 章节列表 -->
		<u-popup v-model="chapter" mode="left" z-index="9000" length="70%" @open="chapterListOpen" @close="chapterListClose">
			<view class="chapter-title" :style="{'background': readTheme.tabBackground}">
				<view class="" style="font-size: 50rpx;margin-bottom: 20rpx;display: flex;justify-content: space-between;">
					<text>{{bookName}}</text>
				</view>
				<view style="display: flex;justify-content: space-between;align-items: center;">
					<text>共{{total}}章</text>
					<u-icon name="arrow-up" size="28"></u-icon>
				</view>
			</view>
			<scroll-view v-if="chapterAllListFlag" scroll-y="true" class="chapter-list" :style="{'background': readTheme.background}"
			 :scroll-into-view="'chapter'+chapterId">
				<view :class="chapterId==item.id?'u-line-1 current-chapter':'u-line-1'" v-for="(item, index) in chapterAllList"
				 :key="index" :id="'chapter'+item.id" :style="'border-bottom: 2rpx solid'+ readTheme.tabBackground +';margin-bottom: 20rpx;padding-bottom: 20rpx;'"
				 @click="handleToChapter(item.book_id,item.id)">{{item.title}}</view>
			</scroll-view>
			<view v-else class="chapter-list" :style="{'background': readTheme.tabBackground, 'display':'flex','justify-content':'center','padding-top':'40rpx'}">
				<u-loading mode="circle"></u-loading>
				<text>列表加载中</text>
			</view>
		</u-popup>

		<!-- 其他设置 -->
		<u-popup v-model="setting" mode="bottom" :mask="false" z-index="9000">
			<view class="setting-box" :style="{'background': readTheme.tabBackground}">
				<view class="setting-item">
					<view class="setting-title">
						字体大小
					</view>
					<view class="setting-content">
						<u-number-box v-model="fontSize" @change="fontSizeChange" :min="12" :max="30" :disabled-input="true"></u-number-box>
					</view>
				</view>
				<view class="setting-item">
					<view class="setting-title">
						页面边距
					</view>
					<view class="setting-content">
						<u-radio-group v-model="pagePadding" @change="setSetting">
							<u-radio name="0"> 无 </u-radio>
							<u-radio name="20"> 小 </u-radio>
							<u-radio name="40"> 中 </u-radio>
							<u-radio name="80"> 大 </u-radio>
						</u-radio-group>
					</view>
				</view>
				<view class="setting-item">
					<view class="setting-title">
						段落距离
					</view>
					<view class="setting-content">
						<u-radio-group v-model="sectionDistance" @change="setSetting">
							<u-radio name="0"> 小 </u-radio>
							<u-radio name="1"> 中 </u-radio>
							<u-radio name="2"> 大 </u-radio>
						</u-radio-group>
					</view>
				</view>
				<view class="setting-item">
					<view class="setting-title">
						行间距离
					</view>
					<view class="setting-content">
						<u-radio-group v-model="lineDistance" @change="setSetting">
							<u-radio name="30"> 小 </u-radio>
							<u-radio name="38"> 中 </u-radio>
							<u-radio name="60"> 大 </u-radio>
						</u-radio-group>
					</view>
				</view>
				<view class="setting-item">
					<view class="setting-title">
						翻页方式
					</view>
					<view class="setting-content">
						<u-radio-group v-model="pageTurnType" @change="pageTurnTypeChange">
							<u-radio name="0"> 滚屏 </u-radio>
							<u-radio name="1"> 上下 </u-radio>
							<u-radio name="2"> 左右 </u-radio>
						</u-radio-group>
					</view>
				</view>
				<view class="setting-item">
					<view class="setting-title">
						滚动动画
					</view>
					<view class="setting-content" style="width:300rpx;margin-left: 20rpx;">
						<u-slider v-model="animateSpeed" :use-slot="true" @end="setSetting">
							<view class="">
								<view class="badge-button">
									{{ animateSpeed == 0 ? '无' : animateSpeed < 50 ? '快' : '慢'  }}
								</view>
							</view>
						</u-slider>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 轻提示 -->
		<u-toast ref="uToast" />

		<!-- 弹窗 -->
		<u-modal v-model="bookShelfFlag" content="喜欢本书就加入书架吧" show-cancel-button confirm-text="加入书架" @confirm="addBookShelfConfirm"
		 @cancel="addBookShelfCancel" async-close></u-modal>
	</view>
</template>

<script>
	import {
		getRead
	} from '../../api/read'
	import {
		getChapterList,
		getAllChapterList
	} from "../../api/chapter";
	import {
		getBookShelfList,
		addBookToShelf,
		delBookFromShelf,
		updateBookShelfList
	} from '../../api/shelf'
	export default {
		data() {
			return {
				loading: false,
				bookId: 0,
				chapterId: 0,
				chapterIndex: 0,
				bookShelfId: 0,
				contentList: [],
				lastChapterData: {},
				currentChapterData: {},
				nextChapterData: {},
				nextChapterDataList: [],
				chapterTitle: '',
				bookName: '',
				currentChapter: 0,
				option: false,
				currentChapterIndex: 0,
				timer: null,
				currentTime: '',
				currentTimeFlag: null,
				currentPage: 1,
				lastPage: 0,
				pageSize: 50,
				chapterAllList: [],
				chapterAllListFlag: false,
				chapterListFlag: true,
				total: 0,
				sliderChapterName: '',
				sliderChapterId: '',
				defaultBrightness: 0,
				brightnessValue: 0,
				brightness: false,
				defaultBrightnessChecked: false,
				chapter: false,
				flag: false,
				bookShelfFlag: false,
				readTheme: [],
				setting: false,
				fontSize: 16,
				fontFamily: 'font-kaiti',
				battery: 60,
				pagePadding: '20',
				sectionDistance: '1',
				lineDistance: '38',
				pageTurnType: '0',
				animateSpeed: 0,
				pushing: false,
				pageHeight: 0,
				playFlag: false
			}
		},
		computed: {
			currentPageFlag() {
				let flag = false;
				if (this.contentList.length != 0) {
					flag = this.contentList[this.currentChapter].index != (this.currentChapterIndex / 100 * this.total).toFixed(0)
				}
				return flag;
			}
		},
		watch: {
			currentChapter(val) {
				this.chapterTitle = this.contentList[val].title;
				this.chapterId = this.contentList[val].chapter_id;
				let _currentChapterIndex = this.currentChapterIndex;
				this.currentChapterIndex = ((this.contentList[val].index / this.chapterAllList.length) * 100)
					.toFixed(0);
				if (this.currentChapterIndex = _currentChapterIndex) {
					this.sliderChapterName = this.contentList[val].title;
					this.sliderChapterId = this.contentList[val].id;
				}
				this.setLastReadBook(this.bookId);
				this.updateBookShelf();
				this.updateBookList();
			},
			currentChapterIndex(val) {
				let _currentPage = (val / 100 * this.total).toFixed(0);
				_currentPage = _currentPage == 0 ? 0 : _currentPage - 1;
				this.sliderChapterName = this.chapterAllList[_currentPage].title;
				this.sliderChapterId = this.chapterAllList[_currentPage].id;
			},
			// #ifdef APP-PLUS
			brightnessValue(val) {
				if (this.defaultBrightnessChecked) {
					this.defaultBrightnessChecked = false;
				}
				uni.setScreenBrightness({
					value: val / 100,
					success: function() {
						console.log('success');
					}
				});
			},
			defaultBrightnessChecked(val) {
				if (val) {
					uni.setScreenBrightness({
						value: this.defaultBrightness / 100,
						success: function() {
							console.log('success');
						}
					});
				} else {
					uni.setScreenBrightness({
						value: this.brightnessValue / 100,
						success: function() {
							console.log('success');
						}
					});
				}
			}
			// #endif
		},
		onPageScroll: _.throttle(function(event) {
			this.getCurrentChapter();
			this.getNextReadContent();
			this.setNextReadContent();
		}, 100, {
			'trailing': false
		}),
		onLoad(option) {
			// #ifdef APP-PLUS
			plus.navigator.setFullscreen(true);
			this.getScreenBrightness();
			this.setLightForever();
			// #endif
			this.init(option);
		},
		onReady() {
			// #ifdef APP-PLUS
			this.getBattery();
			// #endif
		},
		onBackPress(event) {
			if (event.from == 'backbutton') {
				if (this.route_type === 'launch') {
					uni.switchTab({
						url: '/pages/index/index'
					})
					return true;
				}
			}
		},
		onUnload() {
			// #ifdef APP-PLUS  
			plus.navigator.setFullscreen(false);
			uni.setKeepScreenOn({
				keepScreenOn: false
			});
			// #endif
			clearInterval(this.currentTimeFlag);
			this.readTimeEnd = this.getCurrentTime();
			this.setReadTime()
		},
		methods: {
			chapterListOpen() {
				setTimeout(() => {
					this.chapterAllListFlag = true;
				}, 400);
			},
			chapterListClose() {
				this.chapterAllListFlag = false;
			},
			// 初始化
			async init(option) {
				this.loading = true;
				this.bookId = option.id;
				this.chapterId = option.chapter_id;
				if (option.route_type) {
					this.route_type = option.route_type;
				}
				this.getTheme();
				this.getSetting();
				this.handleGetBookShelf(this.bookId);
				await this.getContent(this.bookId, this.chapterId);
				this.loading = false;

				this.sliderChapterId = this.chapterId;
				this.currentTime = this.getCurretnTime();
				this.currentTimeFlag = setInterval(() => {
					this.currentTime = this.getCurretnTime();
				}, 1000);
				this.readTimeStart = this.getCurrentTime();
				await this.getAllChapterList(this.bookId);
				this.setLastReadBook(option.id);
				this.updateBookShelf();
				this.updateBookList();
			},
			// 设置最后阅读缓存
			setLastReadBook(id) {
				let lastReadBook = {
					id: id,
					chapter_id: parseInt(this.chapterAllList[this.currentChapterData.index - 1].id)
				};
				uni.setStorageSync('last_read_book', lastReadBook)
			},
			// 设置屏幕是否常亮
			setLightForever() {
				let lightForever = uni.getStorageSync('lightForever');
				if (lightForever) {
					uni.setKeepScreenOn({
						keepScreenOn: true
					});
				}
			},
			// 设置段落距离
			sectionDistanceFilter(content) {
				let _content = content;
				if (/<br><br>/.test(_content)) {
					switch (this.sectionDistance) {
						case '0':
							_content = _content.replace(/<br><br>/g, '')
							_content = _content.replace(/<br>    /g, '    ')
							break;
						case '1':
							_content = _content.replace(/<br><br>/g, '')
							break;
						case '2':
							break;
						default:
							break;
					}
				} else {
					switch (this.sectionDistance) {
						case '0':
							_content = _content.replace(/<br>    /g, '')
							break;
						case '1':
							_content = _content.replace(/<br>     /g, '<br><br>')

							break;
						case '2':
							_content = _content.replace(/<br>     /g, '<br><br><br><br>')
							break;
						default:
							break;
					}
				}
				return _content
			},
			// 获取电量
			// #ifdef APP-PLUS
			getBattery() {
				var main = plus.android.runtimeMainActivity();
				var Intent = plus.android.importClass('android.content.Intent');
				var recevier = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: (context, intent) => {
						var action = intent.getAction();
						if (action == Intent.ACTION_BATTERY_CHANGED) {
							var level = intent.getIntExtra("level", 0); //电量  
							var voltage = intent.getIntExtra("voltage", 0); //电池电压  
							var temperature = intent.getIntExtra("temperature", 0); //电池温度  
							//如需获取别的，在这里继续写，此代码只提供获取电量  
							console.log(level)
							this.battery = level
						}
					}
				});
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				var filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
				main.registerReceiver(recevier, filter);
			},
			// #endif
			// 设置阅读时间
			setReadTime() {
				let read_time = uni.getStorageSync('read_time');
				if (read_time) {
					let readTime = JSON.parse(read_time);
					if (this.bookId && this.readTimeStart && this.readTimeEnd) {
						let readTimeItem = {
							bookId: this.bookId,
							readTimeStart: this.readTimeStart,
							readTimeEnd: this.readTimeEnd
						};
						readTime.push(readTimeItem)
						uni.setStorageSync('read_time', JSON.stringify(readTime))
					}
				} else {
					if (this.bookId && this.readTimeStart && this.readTimeEnd) {
						let readTimeItem = {
							bookId: this.bookId,
							readTimeStart: this.readTimeStart,
							readTimeEnd: this.readTimeEnd
						};
						let readTime = [];
						readTime.push(readTimeItem)
						uni.setStorageSync('read_time', JSON.stringify(readTime))
					}
				}
			},
			// 获取当前时间 yyyy-mm-dd hh:mm:ss
			getCurrentTime() {
				let myDate = new Date();
				return `${myDate.getFullYear()}/${(myDate.getMonth() + 1) < 10 ? '0' + (myDate.getMonth() + 1) : (myDate.getMonth() + 1)}/${myDate.getDate() < 10 ? '0' + myDate.getDate() : myDate.getDate()} ${myDate.getHours() < 10 ? '0' + myDate.getHours() : myDate.getHours()}:${myDate.getMinutes() < 10 ? '0' + myDate.getMinutes() : myDate.getMinutes()}:${myDate.getSeconds() < 10 ? '0' + myDate.getSeconds() : myDate.getSeconds()}`
			},
			hanleToChooseFontFamily(val) {
				this.fontFamily = val;
				this.setSetting();
			},
			fontSizeChange(value) {
				this.fontSize = value.value
				this.setSetting();
			},
			// 获取字体缓存
			getSetting() {
				let read_setting = uni.getStorageSync('read_setting');
				if (read_setting) {
					read_setting = JSON.parse(read_setting)
					this.fontSize = read_setting.fontSize ? read_setting.fontSize : this.fontSize;
					this.fontFamily = read_setting.fontFamily ? read_setting.fontFamily : this.fontFamily;
					this.pagePadding = read_setting.pagePadding ? read_setting.pagePadding : this.pagePadding;
					this.sectionDistance = read_setting.sectionDistance ? read_setting.sectionDistance : this.sectionDistance;
					this.lineDistance = read_setting.lineDistance ? read_setting.lineDistance : this.lineDistance;
					this.pageTurnType = read_setting.pageTurnType ? read_setting.pageTurnType : this.pageTurnType;
					this.animateSpeed = read_setting.animateSpeed ? read_setting.animateSpeed : this.animateSpeed;
				}
			},
			// 设置字体缓存
			setSetting() {
				let read_setting = {
					'fontSize': this.fontSize,
					'fontFamily': this.fontFamily,
					'pagePadding': this.pagePadding,
					'sectionDistance': this.sectionDistance,
					'lineDistance': this.lineDistance,
					'pageTurnType': this.pageTurnType,
					'animateSpeed': this.animateSpeed
				}
				uni.setStorageSync('read_setting', JSON.stringify(read_setting))
			},
			// 获取主题缓存
			getTheme() {
				let read_theme = uni.getStorageSync('read_theme');
				if (read_theme) {
					this.readTheme = JSON.parse(read_theme)
				} else {
					this.readTheme = this.$store.state.read_theme[0];
				}
			},
			// 切换主题
			handleToChangeTheme() {
				if (this.readTheme.index == 0) {
					this.readTheme = this.$store.state.read_theme[1]
				} else {
					this.readTheme = this.$store.state.read_theme[0];
				}
				this.setTheme();
			},
			// 设置主题缓存
			setTheme() {
				uni.setStorageSync('read_theme', JSON.stringify(this.readTheme))
			},
			// 自定义返回
			haneleToDetail() {
				if (this.route_type === 'launch') {
					uni.switchTab({
						url: '/pages/index/index'
					})
				} else {
					if (!this.flag) {
						this.bookShelfFlag = true;
					} else {
						uni.navigateBack()
					}
				}
			},
			addBookShelfCancel() {
				uni.navigateBack()
			},
			addBookShelfConfirm() {
				this.handleAddBookShelf();
				setTimeout(() => {
					this.bookShelfFlag = false;
					uni.navigateBack();
				}, 1000);
			},
			// 获取章节内容
			getContent(id, chapter_id) {
				return new Promise((resolve, reject) => {
					getRead({
						id,
						chapter_id
					}).then(res => {
						let currentContent = res.data;
						currentContent.chapter_id = chapter_id;
						this.contentList.push(currentContent);
						this.currentChapterData = res.data;
						this.bookName = res.data.name;
						this.chapterTitle = res.data.title;
						this.sliderChapterName = res.data.title;
						resolve('ok')
					})
				})
			},
			// 获取所有章节
			getAllChapterList(id) {
				return new Promise((resolve, reject) => {
					getAllChapterList({
						id
					}).then(res => {
						this.chapterAllList = res.data.chapterList;
						this.currentChapterIndex = ((this.contentList[this.currentChapter].index / this.chapterAllList.length) * 100)
							.toFixed(0);
						this.total = res.data.chapterList.length;
						resolve('ok')
					})
				})
			},
			// 页面滚动
			scrollView: _.throttle(function() {
				this.getCurrentChapter();
				this.getNextReadContent();
				this.setNextReadContent();
			}, 100, {
				'trailing': false
			}),
			// 获取当前可视区域的章节信息
			getCurrentChapter() {
				const _self = this;
				const query = uni.createSelectorQuery().in(this);
				query.select("#chapter" + _self.contentList[this.currentChapter].index).boundingClientRect(data => {
					let bottom = data.bottom;
					let height = data.height;
					if (bottom < 0) {
						_self.currentChapter = _self.currentChapter + 1;
					} else if (bottom > height) {
						_self.currentChapter = _self.currentChapter - 1;
					}
				}).exec()
			},
			// 获取上一章节内容
			getLastReadContent() {
				if (this.currentChapterData.last_chapterId == 0) {
					return;
				}
				getRead({
					id: this.currentChapterData.id,
					chapter_id: this.currentChapterData.last_chapterId
				}).then(res => {
					let currentContent = res.data;
					currentContent.chapter_id = this.currentChapterData.last_chapterId;
					this.lastChapterData = res.data;
				});
			},
			// 获取下一章节内容
			getNextReadContent: _.throttle(function() {
				if (this.currentChapterData.next_chapterId == 0) {
					return
				}
				if (this.pushing) {
					return;
				}
				if (this.nextChapterDataList.length < 3) {
					this.pushing = true;
					getRead({
						id: this.currentChapterData.id,
						chapter_id: this.currentChapterData.next_chapterId
					}).then(res => {
						let data = res.data;
						data.chapter_id = this.currentChapterData.next_chapterId;
						this.nextChapterData = data;
						this.nextChapterDataList.push(data);
						this.currentChapterData = this.nextChapterData;
						this.pushing = false;
					})
				}
			}, 100, {
				'trailing': false
			}),
			// 设置下一章节内容
			setNextReadContent: _.throttle(function() {
				if (this.nextChapterDataList.length == 0) {
					return;
				} else {
					if (parseInt(this.nextChapterDataList[0].index) - parseInt(this.contentList[this.currentChapter].index) < 3) {
						this.contentList.push(this.nextChapterDataList.shift());
					}
				}
			}, 100, {
				'trailing': false
			}),
			// 设置上一章节内容
			setLastReadContent() {
				this.contentList.unshift(this.lastChapterData);
				this.currentChapterData = this.lastChapterData;
				this.lastChapterData = {};
			},
			// 打开菜单
			handleToMenu: _.throttle(function(e) {
				let offsetY = this.windowHeight / 3;
				let currentY = e.target.y;
				if (currentY <= offsetY) {
					if (e.currentTarget.dataset.type == 'scroll') {
						if (this.pageHeight == 0) {
							this.$refs.uToast.show({
								title: '到顶了!',
								type: 'warning'
							})
						} else {
							if (this.pageHeight < (this.screenHeight - 30)) {
								this.pageHeight = 0;
							} else {
								this.pageHeight = this.pageHeight - (this.screenHeight - 30);
							}
							uni.pageScrollTo({
								scrollTop: this.pageHeight,
								duration: this.animateSpeed * 10
							});
						}
					}
				} else if (offsetY <= currentY && currentY <= offsetY * 2) {
					console.log('center')
					this.option = !this.option;
				} else if (currentY >= offsetY * 2 && currentY <= this.windowHeight) {
					if (e.currentTarget.dataset.type == 'scroll') {
						this.pageHeight = this.pageHeight + (this.screenHeight - 30);
						uni.pageScrollTo({
							scrollTop: this.pageHeight,
							duration: this.animateSpeed * 10
						});
					}
				}
			}, 200, {
				'trailing': false
			}),
			// 切换翻页模式时候 重新加载页面高度
			refreshPage() {
				uni.redirectTo({
					url: `/pages/read/read?id=${this.bookId}&chapter_id=${this.contentList[this.currentChapter].chapter_id}`
				})
			},
			pageTurnTypeChange() {
				this.setSetting();
				this.refreshPage();
			},
			// 获取当前时间
			getCurretnTime() {
				let myDate = new Date();
				return `${myDate.getHours()}:${myDate.getMinutes() < 10 ? '0' + myDate.getMinutes() : myDate.getMinutes()}`
			},
			// 菜单弹出层打开时
			optionOpen() {
				// #ifdef APP-PLUS
				plus.navigator.setFullscreen(false);
				// #endif
			},
			// 菜单弹出层关闭时
			optionClose() {
				// #ifdef APP-PLUS
				plus.navigator.setFullscreen(true);
				// #endif
			},
			// 跳转到上一章
			handleToLastChapter() {
				if (this.contentList[this.currentChapter].last_chapterId == 0) {
					this.$refs.uToast.show({
						title: '已经是第一章了!',
						type: 'warning'
					})
				} else {
					uni.redirectTo({
						url: `/pages/read/read?id=${this.contentList[this.currentChapter].id}&chapter_id=${this.contentList[this.currentChapter].last_chapterId}`
					})
				}
			},
			// 跳转到下一章
			handleToNextChapter() {
				if (this.contentList[this.currentChapter].next_chapterId == 0) {
					this.$refs.uToast.show({
						title: '已经是最后一章了!',
						type: 'warning'
					})
				} else {
					uni.redirectTo({
						url: `/pages/read/read?id=${this.contentList[this.currentChapter].id}&chapter_id=${this.contentList[this.currentChapter].next_chapterId}`
					})
				}
			},
			currentChapterIndexChange() {

			},
			// 跳转滑动组件显示的章节
			handleToSliderChapter() {
				uni.redirectTo({
					url: `/pages/read/read?id=${this.contentList[this.currentChapter].id}&chapter_id=${this.sliderChapterId}`
				})
			},
			// 获取屏幕亮度
			getScreenBrightness() {
				uni.getScreenBrightness({
					success: (res) => {
						this.defaultBrightness = (res.value * 100).toFixed(0);
						this.brightnessValue = (res.value * 100).toFixed(0);
					}
				});
			},
			handleToBrightness() {
				this.option = !this.option;
				this.brightness = !this.brightness;
			},
			handleToChapterList() {
				this.option = !this.option;
				this.chapter = !this.chapter;
			},
			// 跳转章节
			handleToChapter(id, chapter_id) {
				uni.redirectTo({
					url: `/pages/read/read?id=${id}&chapter_id=${chapter_id}`
				})
			},
			// 查询书架缓存
			handleGetBookShelf(id) {
				if (this.access_token) {
					let header = {
						Authorization: 'Bearer ' + this.access_token
					}
					getBookShelfList(header).then(res => {
						let bookshelfList = [];
						if (res.code == 200) {
							bookshelfList = res.data.bookList;
						}
						bookshelfList.forEach(item => {
							if (item.book_id == id) {
								this.flag = true;
								this.bookShelfId = item.book_shelf_id;
							}
						})
					})
				} else {
					try {
						let bookShelf = uni.getStorageSync("bookShelf");
						if (bookShelf) {
							let _bookShelf = JSON.parse(bookShelf);
							if (_bookShelf[id]) {
								this.flag = true;
							}
						}
					} catch (e) {
						console.log(e);
					}
				}
			},
			// 加入or撤出书架
			handleAddBookShelf: _.debounce(function() {
				if (this.access_token) {
					if (this.flag) { // 撤出
						delBookFromShelf({
							Authorization: 'Bearer ' + this.access_token
						}, {
							'bookShelfId': this.bookShelfId
						}).then(res => {
							this.flag = false;
							this.$refs.uToast.show({
								title: '成功撤出书架',
								type: 'success',
								position: 'top'
							})
						})
					} else { // 加入
						addBookToShelf({
							Authorization: 'Bearer ' + this.access_token
						}, {
							'bookId': this.currentChapterData.id,
							'lastReadChapter': this.chapterAllList[this.currentChapterData.index - 1].id,
							'index': this.currentChapterData.index - 1
						}).then(res => {
							this.flag = true;
							this.$refs.uToast.show({
								title: '成功加入书架',
								type: 'success',
								position: 'top'
							})
						})
					}
				} else {
					if (this.flag) {
						let bookShelf = uni.getStorageSync("bookShelf");
						if (bookShelf) {
							let _bookShelf = JSON.parse(bookShelf);
							if (_bookShelf[this.currentChapterData.id]) {
								delete _bookShelf[this.currentChapterData.id];
								uni.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
								this.flag = false;
								this.$refs.uToast.show({
									title: '成功撤出书架',
									type: 'success',
									position: 'top'
								})
							}
						}
					} else {
						let bookShelf = uni.getStorageSync("bookShelf");
						let bookList = uni.getStorageSync("bookList");
						let _bookShelf = bookShelf ? JSON.parse(bookShelf) : {};
						let _bookList = bookList ? JSON.parse(bookList) : {
							'type': null,
							'writer': null,
							'is_over': null,
							'image': null
						};
						_bookShelf[this.currentChapterData.id] = {
							index: this.currentChapterData.index - 1,
							last_read_chapter: this.chapterAllList[this.currentChapterData.index - 1].id,
							book_id: this.currentChapterData.id,
							chapterCount: this.total,
							name: this.bookName,
							type: _bookList[this.currentChapterData.id].type,
							writer: _bookList[this.currentChapterData.id].writer,
							is_over: _bookList[this.currentChapterData.id].is_over,
							image: _bookList[this.currentChapterData.id].image
						};
						uni.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
						this.flag = true;
						this.$refs.uToast.show({
							title: '成功加入书架',
							type: 'success',
							position: 'top'
						})
					}
				}
			}, 500, {
				'leading': true,
				'trailing': false
			}),
			// 更新书架信息
			updateBookShelf() {
				if (this.access_token) {
					if (this.flag) {
						updateBookShelfList({
							Authorization: 'Bearer ' + this.access_token
						}, {
							'bookId': this.currentChapterData.id,
							'lastReadChapter': this.chapterAllList[this.currentChapterData.index - 1].id,
							'index': this.currentChapterData.index - 1
						})
					}
				} else {
					if (this.flag) {
						let bookShelf = uni.getStorageSync("bookShelf");
						let bookList = uni.getStorageSync("bookList");
						let _bookShelf = bookShelf ? JSON.parse(bookShelf) : {};
						let _bookList = bookList ? JSON.parse(bookList) : {
							'type': null,
							'writer': null,
							'is_over': null,
							'image': null
						};
						_bookShelf[this.currentChapterData.id] = {
							index: this.currentChapterData.index - 1,
							last_read_chapter: this.chapterAllList[this.currentChapterData.index - 1].id,
							book_id: this.currentChapterData.id,
							chapterCount: this.total,
							name: this.bookName,
							type: _bookList[this.currentChapterData.id].type,
							writer: _bookList[this.currentChapterData.id].writer,
							is_over: _bookList[this.currentChapterData.id].is_over,
							image: _bookList[this.currentChapterData.id].image
						};
						uni.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
					}
				}
			},
			// 更新书籍信息
			updateBookList() {
				let bookList = uni.getStorageSync('bookList');
				if (bookList) {
					let _bookList = JSON.parse(bookList)
					if (_bookList[this.currentChapterData.id]) {
						let myDate = new Date();
						_bookList[this.currentChapterData.id].lastReadChapter = this.chapterAllList[this.currentChapterData.index - 1].id;
						_bookList[this.currentChapterData.id].lastReadChapterIndex = this.currentChapterData.index - 1;
						_bookList[this.currentChapterData.id].lastReadChapterName = this.chapterAllList[this.currentChapterData.index - 1]
							.title;
						_bookList[this.currentChapterData.id].lastReadDate =
							`${myDate.getFullYear()}-${(myDate.getMonth() + 1) < 10 ? '0' + (myDate.getMonth() + 1) : (myDate.getMonth() + 1)}-${myDate.getDate() < 10 ? '0' + myDate.getDate() : myDate.getDate()}`
						_bookList[this.currentChapterData.id].lastReadTime =
							`${myDate.getHours() < 10 ? '0' + myDate.getHours() : myDate.getHours()}:${myDate.getMinutes() < 10 ? '0' + myDate.getMinutes() : myDate.getMinutes()}:${myDate.getSeconds() < 10 ? '0' + myDate.getSeconds() : myDate.getSeconds()}`
						uni.setStorageSync("bookList", JSON.stringify(_bookList));
					}
				}
			},
			// 设置
			handleToSetting() {
				this.option = !this.option;
				this.setting = !this.setting;
			},
			// 语音播放
			handleToPlay() {
				this.playFlag = !this.playFlag;
				if (this.playFlag) {
					
				} else {

				}
			}
		}
	}
</script>

<style scoped>
	.read-load {
		position: fixed;
		top: 0;
		left: 0;
		height: 100vh;
		width: 100vw;
		z-index: 10001;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.read-box {
		min-height: 3000rpx;
	}

	.read-top {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		padding: 10rpx 10vw 10rpx 10vw;
		z-index: 10;
	}

	.top-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.read-info {
		font-size: 26rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.battery {
		font-size: 14rpx;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		border: 2rpx solid currentColor;
		position: relative;
		margin-right: 10rpx;
		width: 32rpx;
		height: 20rpx;
		color: midnightblue;
		border-radius: 2rpx;
		background-image: linear-gradient(to right, #33CC00, #66CC33);
		background-repeat: no-repeat;
		background-position: 0px 100%;
		top: 2rpx;
	}

	.battery::after {
		content: '';
		position: absolute;
		width: 6rpx;
		height: 12rpx;
		background-color: currentColor;
		top: 2rpx;
		right: -6rpx;
	}

	.read-title {
		font-weight: bold;
	}

	.slot-wrap {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		width: 100%;
		padding: 0 20px;

	}

	.slider-box {
		position: fixed;
		bottom: 150px;
		left: 10vw;
		width: 80vw;
		padding: 10px 5vw;
		border-radius: 4px;
	}

	.chapter-slider {
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 8vw;
	}

	.screen-box {
		height: 160rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 4vw;
	}

	.chapter-title {
		height: 12vh;
		padding: 30rpx;
	}

	.chapter-list {
		height: 88vh;
		width: 100%;
		padding: 20rpx 30rpx 0 30rpx;
	}

	.setting-box {
		padding: 40rpx;
	}

	.setting-item {
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.setting-item:last-child {
		margin-bottom: 0;
	}

	.setting-title {
		margin-right: 20rpx;
	}

	.setting-content {}

	.font-family {
		border: 2rpx solid #000000;
		border-radius: 40rpx;
		padding: 6rpx 20rpx;
		margin-right: 10rpx;
	}

	.active {
		border-color: #2B85E4;
		color: #2B85E4;
	}

	.current-chapter {
		color: rgb(146, 200, 255);
	}

	.status-bar {
		height: var(--status-bar-height);
		width: 100%;
	}

	.scroll-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		height: 100vh;
		width: 100vw;
		background-color: transparent;
		z-index: 1000;
		touch-action: none;
	}

	.badge-button {
		padding: 4rpx 6rpx;
		background-color: #2B85E4;
		color: #fff;
		border-radius: 10rpx;
		font-size: 30rpx;
		line-height: 1;
	}
</style>
